const express = require("express");
const cors = require("cors");
const db = require("./libs/DBHelper");

let server = express();
//配置静态资源
server.use(express.static("./../src"));
server.use(express.static("./../images"));


//配置中间件
//post能够快速使用 body
server.use(express.urlencoded({ extended: false }));
server.use(express.json());

server.use(cors());//配置跨域

server.get("/index", function (request, response) {
    console.log(2222222);
    response.end("hi...");
})

server.post("/account/register", async (request, response) => {
    //1.接受前端的数据 (用户名和密码)
    let { user, pwd } = request.body;
    //2. 准备sql语句
    let sql = "SELECT `uId`,`uName`,`uSex`,`uPhone` FROM `userinfo` WHERE uname=? AND upwd=? AND ustatus=1;";
    let parmas = [
        user,
        pwd
    ]
    try {
        let result = await db.exec(sql, parmas);
        if (result && result.length >= 1) {
            response.json({
                msg: "登录成功!",
                data: result,
                code: 200
            })
        } else {
            response.json({
                msg: "登录失败!",
                code: 200
            })
        }

    } catch (error) {
        response.json({
            msg: "登录失败!",
            err: error,
            code: -200
        })
    }
})


server.post("/account/reg", async function (request, response) {
    //1.接受参数 
    let { user, pwd, sex, phone } = request.body;
    //2.准备sql语句
    let sql = "INSERT INTO `userinfo` (`uName`,`uPwd`,`uSex`,`uPhone`)VALUES(?,?,?,?);";
    //参数
    let parmas = [user, pwd, sex, phone];

    try {
        let result = await db.exec(sql, parmas);
        //注意:除了查询返回的是数组,
        //其他 (插入,修改,删除)返回的 受影响行数
        //不是undefined并且受影响行数大于等于1
        console.log(result);
        let isReg = result && result.affectedRows;
        response.json({
            msg: isReg ? "注册成功!" : '注册失败!',
            code: 200
        })
    } catch (error) {
        response.json({
            msg: '注册失败!',
            err: error,
            code: -200
        })
    }
})
//设置端口
server.listen(8080, () => {
    console.log("服务启动完毕!");
})